﻿using System.Text;

namespace XxlJobDotNetCore.RequestBase
{
    /// <summary>
    /// Http请求
    /// </summary>
    public class HttpRequest
    {
        private readonly string  _baseUrl;
        public HttpRequest(IConfiguration configuration)
        {
            _baseUrl = configuration["BaseApiUrl"]??"";
        }
        public async Task<string> PostAsync(string url)
        {
            url = $"{_baseUrl}/{url}";
            using var httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(1000000);
            using (HttpResponseMessage httpResponse = await httpClient.PostAsync(url, null))
            {
                if (httpResponse.IsSuccessStatusCode)
                {
                    var readAsStringAsync = await httpResponse.Content.ReadAsStringAsync();
                    return readAsStringAsync;
                }
                else
                {
                    return "http请求错误：" + httpResponse.StatusCode.ToString();
                }
                httpResponse.Dispose();
            }
            return null;
        }
        public async Task<string> GetAsync(string url)
        {
            url = $"{_baseUrl}/{url}";
            using var httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromSeconds(1000000);
            using HttpResponseMessage httpResponse = await httpClient.GetAsync(url);
            if (httpResponse.IsSuccessStatusCode)
            {
                var readAsStringAsync = await httpResponse.Content.ReadAsStringAsync();
                httpClient.Dispose();
                return readAsStringAsync;
            }
            else
            {
                httpClient.Dispose();
                return "http请求错误：" + httpResponse.StatusCode.ToString();
            }           
        }
    }
}
